import { qiankunWindow } from 'vite-plugin-qiankun/dist/helper';
import { createRouter, createWebHistory } from 'vue-router';
import Home from '../views/Home.vue';

/*
  如果是qiankun环境 routes 的 path 前面加 /sub 适配主子应用路径问题
  主应用配置的activeRule 为/sub  所以 子应用的 路由 需要 加 /sub 前缀
*/
function addSubPrefix(routes) {
  return routes.map((route) => {
    route.path = '/sub' + route.path;
    return route;
  });
}

const routes = [
  {
    path: '/',
    name: 'Home',
    redirect: '/sub/home',
  },
  {
    path: '/home',
    name: 'Home',
    component: Home,
  },
  {
    path: '/about',
    name: 'About',
    component: () => import('../views/About.vue'),
  },
];

const router = createRouter({
  history: createWebHistory(),
  routes: qiankunWindow.__POWERED_BY_QIANKUN__ ? addSubPrefix(routes) : routes,
});

router.beforeEach((to, from, next) => {
  const basePath = qiankunWindow.__POWERED_BY_QIANKUN__ ? '/sub' : '/';
  console.log('子应用路由守卫执行:', {
    to: to.fullPath,
    from: from.fullPath,
    basePath,
    isQiankun: qiankunWindow.__POWERED_BY_QIANKUN__,
  });
  //如果是qiankun 第一次进来的加载页面的时候 加上子应用前缀  后面再进来的时候 就不需要加前缀了 直接next()
  if (qiankunWindow.__POWERED_BY_QIANKUN__ && !to.path.startsWith(basePath)) {
    next({ path: basePath + to.path, query: to.query });
    return;
  }

  next();
});

export default router;
